package com.cloud.common.exception;

import com.cloud.common.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author wangjian
 * @create: 2018年9月9日 下午10:52:55
 */
@RestControllerAdvice
public class GlobalExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult<Void> validatedBindException(BindException e) {
        logger.error("自定义验证异常", e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return new AjaxResult<Void>().error(message);
    }

    /**
     * 自定义业务异常
     */
    @ExceptionHandler(CloudException.class)
    public AjaxResult<Void> validatedBindException(CloudException e) {
        logger.error("自定义业务异常", e);
        return new AjaxResult<Void>().error(e.getCode(), e.getMsg());
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public AjaxResult<Void> handleException(HttpRequestMethodNotSupportedException e) {
        logger.error("请求方式不支持异常:", e);
        return new AjaxResult<Void>().error("不支持' " + e.getMethod() + "'请求");
    }


    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult<Void> handle(Exception e) {
        logger.error("系统异常:", e);
        return new AjaxResult<Void>().error("系统异常" + e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult<Void> notFount(RuntimeException e) {
        logger.error("运行时异常:", e);
        return new AjaxResult<Void>().error("运行时异常:" + e.getMessage());
    }

}
